package api

import (
	"encoding/json"
	"errors"
	
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"collecter/app/cache"
	"collecter/app/common/enum"
	"collecter/app/common/helper"
	"collecter/app/controller"
	"collecter/app/model"
)

type UserController struct {
	controller.BaseController
}

func (c *UserController) Profile(ctx *gin.Context) {
	var user model.Users
	if val, err := c.GetUserInfo(); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	} else {
		user = *val
	}
	user.Password = ""
	c.FormatReturn(enum.SUCCESS, user)
}

func (c *UserController) Modify(ctx *gin.Context) {
	type inType struct {
		Nickname string `json:"nickname"`
		Avatar   string `json:"avatar"`
	}
	var inData inType
	if err := controller.Ctx.BindJSON(&inData); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	}
	var refreshToken string
	if val, err := c.GetRefreshToken(); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	} else {
		refreshToken = val
	}
	var user model.Users
	user.RefreshToken = refreshToken
	user.Status = enum.STATUS_ENABLED
	if err := helper.Db.Where(&user).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.FormatReturn(enum.FAILED, "", "用户不存在")
		}
		c.FormatReturn(enum.FAILED, "", err.Error())
	}
	if len(inData.Nickname) > 0 {
		user.Nickname = inData.Nickname
	}
	if len(inData.Avatar) > 0 {
		if !helper.RegExpVerify(inData.Avatar, "url") {
			c.FormatReturn(enum.FAILED, "", "头像内容格式错误")
		}
		user.Avatar = inData.Avatar
	}
	if err := helper.Db.Updates(&user).Error; err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	}

	user.Password = ""
	cacheKey := enum.USER_LOGIN_INFO + user.RefreshToken
	var userJson []byte
	if val, err := json.Marshal(user); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	} else {
		userJson = val
	}
	if err := cache.Cacher.Set(cacheKey, userJson, enum.REFRESH_TOKEN_EXPIRE); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	}

	c.FormatReturn(enum.SUCCESS, "")
}
